// export const baseUrl = 'http://localhost:1107/api';
const db = (database) => {
    const collect = uniCloud.database().collection(database)
    // 统一对返回的promise做错误检查，只需要考虑数据处理
    const execute = async (operation, toast = null) => {
        try {
            const {
                result
            } = await operation();
            if (result.errCode !== 0) {
                uni.showToast({
                    title: result.message,
                    icon: 'none'
                })
                return false
            }
            toast && uni.showToast({
                title: typeof toast === 'boolean' ? '操作成功' : toast,
                icon: 'none'
            })
            return result;
        } catch (error) {
            console.error(`Database operation error: ${operation.name}`, error);
            return uni.showToast({
                title: error,
                icon: 'none'
            })
        }
    };
    return {
        $: () => collect,
        /**
         * 新增数据
         * @param {Object} data - 写入的数据
         */
        add: async (option = {}) => {
            return execute(() => collect.add(option.data || option), option.toast);
        },
        /**
         * 查询数据
         * @param {Object} [option={}] - 条件
         */
        get: async (option = {}) => {
            return execute(() => collect.where({
                ...option.where,
                delete: false
            }).orderBy(option.orderBy).get(), option.toast);
        },
        /**
         * 更新数据
         * @param {Object} data - 写入的数据
         * @param {Object} [option={}] - 条件
         */
        update: async (option = {}) => {
            console.log(option)
            return execute(() => collect.where(option.where).update(option.data), option.toast);
        },
        /**
         * 删除数据
         * @param {Object} [option={}] - 条件
         */
        remove: async (option = {}) => {
            // 假删除
            return execute(() => collect.where(option.where).update({
                delete: true
            }), option.toast);
            // return execute(() => collect.where(option).remove(), toast);
        },

    }
}

export default db